package com.galeno.day09.test;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.Map;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/2622:30
 * 设置状态的TTL（TimeToLive）即设置状态的存活时间
 * 默认情况，状态的数据会一直保存，但是有的数据，以后就不再使用了，如果还在状态中存储，浪费更多的资源，checkpoint的数据会越来越多
 * 我们也可以设置状态的存活时间，以后超时的状态，Flink会清除，这样更加节省资源
 * 需求：统计最近两小时的成交金额（保留当前小时和上一个小时的数据）
 * 为了效果演示更加明显，设置状态的存活时间为1分钟
 */
public class ValueStateTTLDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //商品分类，商品总金额
        //家具,1000
        DataStreamSource<String> lines = env.socketTextStream("192.168.77.3", 9999);
        SingleOutputStreamOperator<Tuple2<String, Double>> tpStream = lines.map(new MapFunction<String, Tuple2<String, Double>>() {
            @Override
            public Tuple2<String, Double> map(String value) throws Exception {
                String[] split = value.split(",");
                return Tuple2.of(split[0], Double.parseDouble(split[1]));
            }
        });
        KeyedStream<Tuple2<String, Double>, String> keyedStream = tpStream.keyBy(x -> x.f0);
        SingleOutputStreamOperator<Tuple3<String, String, Double>> process = keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, Double>, Tuple3<String, String, Double>>() {
            private transient MapState<String, Double> mapState;
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

            @Override
            public void open(Configuration parameters) throws Exception {
                MapStateDescriptor<String, Double> stringDoubleMapStateDescriptor = new MapStateDescriptor<>("min-state", String.class, Double.class);
                /**
                 * 给状态描述器设置TTL
                 */
                StateTtlConfig ttlConfig = StateTtlConfig.newBuilder(Time.minutes(1))
                        .build();//状态保存1分钟
                //将TTLconfig关联到状态描述器
                stringDoubleMapStateDescriptor.enableTimeToLive(ttlConfig);
                mapState = getRuntimeContext().getMapState(stringDoubleMapStateDescriptor);


            }

            @Override
            public void processElement(Tuple2<String, Double> value, Context ctx, Collector<Tuple3<String, String, Double>> out) throws Exception {
                Double current = value.f1;
                long currentTimeMillis = System.currentTimeMillis();
                String timeStr = sdf.format(currentTimeMillis);
                Double history = mapState.get(timeStr);
                if (history == null) {
                    history = 0.0;
                }
                current += history;
                mapState.put(timeStr, current);
//                Iterator<Map.Entry<String, Double>> entryIterator = mapState.entries().iterator();
////                while (entryIterator.hasNext()) {
////                    Map.Entry<String, Double> entry = entryIterator.next();
////                    out.collect(Tuple3.of(value.f0, entry.getKey(), entry.getValue()));
////                }
                out.collect(Tuple3.of(value.f0, timeStr, current));


            }
        });
        process.print();
        env.execute();


    }
}
